<?php defined('SYSPATH') or die('No direct script access.');
/**
 * JSON 功能增强
 *
 * @author  Yellow.Chow <aultoale@gmail.com>
 * @version $Id: json.php 285 2012-06-29 02:36:31Z yellow.chow $
 * @license http://www.gnu.org/licenses/gpl-3.0.html    GPL 3
 */
abstract class JSON
{

    /**
     * 格式化 JSON 数据
     *
     * @param  string  $json
     * @return string
     */
    public static function format($json)
    {
        $result      = '';
        $pos         = 0;
        $strLen      = strlen($json);
        $indentStr   = "\t";
        $newLine     = "\n";
        $prevChar    = '';
        $outOfQuotes = true;

        for ($i = 0; $i <= $strLen; $i++) {

            // Grab the next character in the string.
            $char = substr($json, $i, 1);

            // Are we inside a quoted string?
            if ($char == '"' AND $prevChar != '\\')
            {
                $outOfQuotes = ! $outOfQuotes;

            // If this character is the end of an element,
            // output a new line and indent the next line.
            }
            elseif (($char == '}' OR $char == ']') AND $outOfQuotes)
            {
                $result .= $newLine;
                $pos --;
                for ($j = 0; $j < $pos; $j++)
                {
                    $result .= $indentStr;
                }
            }

            // Add the character to the result string.
            $result .= $char;

            // If the last character was the beginning of an element,
            // output a new line and indent the next line.
            if (($char == ',' OR $char == '{' OR $char == '[') AND $outOfQuotes)
            {
                $result .= $newLine;
                if ($char == '{' OR $char == '[')
                {
                    $pos ++;
                }

                for ($j = 0; $j < $pos; $j++)
                {
                    $result .= $indentStr;
                }
            }

            $prevChar = $char;
        }

        return $result;
    }

    /**
     * 将 array 转换为 JSON 数据
     *
     * @param  array  $data
     * @param  bool   $format
     * @param  bool   $un_unicode
     * @return string
     */
    public static function encode($data, $format = FALSE, $un_unicode = TRUE)
    {
        $json = json_encode($data);

        if ($format === TRUE)
        {
            $json = JSON::format($json);
        }

        if ($un_unicode === TRUE)
        {
            //$json = preg_replace("#\\\u([0-9a-f]+)#ie", "iconv('UCS-2', 'UTF-8//IGNORE', pack('H4', '\\1'))", $json);
        }

        return $json;
    }

    /**
     * 将 JSON 数据转换为 array
     *
     * @param  array  $data
     * @param  bool   $to_assoc
     * @return string
     */
    public static function decode($json, $to_assoc = FALSE)
    {
        return json_decode($json, $to_assoc);
    }

}